<?php
/**
 * DBERP 进销存系统
 *
 * ==========================================================================
 * @link      http://www.dberp.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   http://www.dberp.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\View\Helper;

use Admin\Data\Common;
use Admin\Entity\PrintTemplate;
use Doctrine\ORM\EntityManager;
use Laminas\Config\Factory;
use Laminas\Form\Element\Csrf;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Helper\AbstractHelper;

class AdminHelper extends AbstractHelper
{
    private $entityManager;
    private $translator;
    private $request;
    private $i18nSessionContainer;

    private $csrfValue = '';
    private $routeMatch;

    public function __construct(
        EntityManager   $entityManager,
        Translator      $translator,
        $request,
        $i18nSessionContainer,
        $routeMatch
    )
    {
        $this->entityManager    = $entityManager;
        $this->translator       = $translator;
        $this->request          = $request;
        $this->i18nSessionContainer = $i18nSessionContainer;
        $this->routeMatch       = $routeMatch;
    }

    public function appType($type)
    {
        $typeArray = Common::appType($this->translator);
        return $typeArray[$type];
    }

    public function erp($name, $type = 'base', $configFile = 'config')
    {
        return Common::configValue($type, $configFile)[$name] ?? null;
    }

    /**
     * 商品默认图片的宽高
     * @return string
     */
    public function defaultGoodsImageWidth(): string
    {
        $imageWidth = Common::configValue('other', 'config')['image_width'] ?? 0;
        if ($imageWidth <= 0) return 'width: 50px;height: 50px;';

        return 'width: '.$imageWidth.'px;height: '.$imageWidth.'px;';
    }

    /**
     * 判断是否为自定义打印
     * @param $printTemplateCode
     * @return array|false[]
     */
    public function erpPrintTemplateState($printTemplateCode): array
    {
        $printTemplateInfo = $this->entityManager->getRepository(PrintTemplate::class)->findOneBy(['templateCode' => $printTemplateCode]);
        if ($printTemplateInfo == null || $printTemplateInfo->getTemplateState() != 1) return ['state' => false];

        return ['state' => true, 'templateBody' => $printTemplateInfo->getTemplateBody(), 'templateCode' => $printTemplateInfo->getTemplateCode()];
    }

    /**
     * 当前语言
     * @return mixed|string
     */
    public function erpLanguage()
    {
        if (!file_exists('data/moduleData/System/language.php')) return '';

        if (!empty($this->i18nSessionContainer->language)) return $this->i18nSessionContainer->language;
        else {
            $languageArray = include "data/moduleData/System/language.php";
            return $languageArray['defaultLanguage'];
        }

    }

    /**
     * 语言切换信息
     * @return array|mixed
     */
    public function erpMoreLanguage()
    {
        if (!file_exists('data/moduleData/System/language.php')) return [];

        $languageArray = include "data/moduleData/System/language.php";

        return $languageArray['languageTitle'];
    }

    /**
     * 创建get操作的CSRF Token
     * @return string
     */
    public function getCsrfValue()
    {
        if(empty($this->csrfValue)) {
            $csrf = new Csrf('queryToken');
            $csrf->setOptions(['csrf_options' => ['timeout' => 900]]);
            $this->csrfValue = $csrf->getValue();
        }
        return $this->csrfValue;
    }

    /**
     * 返回分页url的Query字符串，去除page
     * @return bool|string
     */
    public function pagesQuery()
    {
        $queryStr = $this->request->getServer()->get('QUERY_STRING');
        if(!empty($queryStr)) {
            if(strpos($queryStr, 'page=') !== false) {
                $num = strpos($queryStr, '&');
                if($num) return substr($queryStr, $num);
                else return '';
            } else return '&'.$queryStr;
        }
        return $queryStr;
    }

    public function getRoute()
    {
        if($this->routeMatch == null) return false;

        return $this->routeMatch->getMatchedRouteName();
    }

    public function getModule()
    {
        if($this->routeMatch == null) return false;

        $controller = $this->routeMatch->getParam('controller');
        $module     = $this->routeMatch->getParam('__NAMESPACE__');

        $controller = explode('\\', $controller);
        $module     = explode('\\', $module);
        if($module[0] === '' && count($controller) === 3) {
            $module[0] = $controller[0];
        }

        return $module[0];
    }

    public function getController()
    {
        if($this->routeMatch == null) return false;

        $controller = $this->routeMatch->getParam('controller');
        $controller = explode('\\', $controller);
        return array_pop($controller);
    }

    public function getAction()
    {
        if($this->routeMatch == null) return false;

        return $this->routeMatch->getParam('action');
    }

    /**
     * 获取扩展的url信息
     * @return array|\Laminas\Config\Config
     */
    public function extendAdminUrlArray()
    {
        if (file_exists('data/moduleData/Plugin/adminUrl.ini')) return Factory::fromFile('data/moduleData/Plugin/adminUrl.ini');
        return [];
    }

    /**
     * 扩展form
     * @param $extendForm
     * @return string
     */
    public function showExtendForm($extendForm): string
    {
        $extendFormHtml = '';
        foreach ($extendForm['formExtend'] as $formInputValue) {
            $extendFormHtml .= '<div class="form-group">';
            $extendFormHtml .= '<label class="col-sm-2 control-label">'.$formInputValue['inputTitle'].'</label>';
            $extendFormHtml .= '<div class="col-sm-'.$formInputValue['classSpanNum'].'"'.(isset($formInputValue['style']) ? ' '.$formInputValue['style'] : '').'>';

            if (isset($formInputValue['type'])) {
                if ($formInputValue['type'] == 'checkbox') {
                    $extendFormHtml .= '<div class="checkbox"><label>';
                    $extendFormHtml .= $this->getView()->formElement($extendForm['form']->get($formInputValue['inputName']));
                    $extendFormHtml .= $this->getView()->formElementErrors($extendForm['form']->get($formInputValue['inputName']), ['class'=>'error-message']);
                    $extendFormHtml .= $this->translator->translate('启用');
                    $extendFormHtml .= '</label></div>';
                }
            } elseif (!empty($formInputValue['inputName'])) {
                $extendFormHtml .= $this->getView()->formElement($extendForm['form']->get($formInputValue['inputName']));
                $extendFormHtml .= $this->getView()->formElementErrors($extendForm['form']->get($formInputValue['inputName']), ['class'=>'error-message']);
            }

            $staticBody = '';
            if (!empty($formInputValue['staticBody'])) {
                $staticBody = '<p class="form-control-static">'.$formInputValue['staticBody'].'</p>';
            }

            $extendFormHtml .= !empty($formInputValue['inputName']) ? '</div>'.$staticBody : $staticBody.'</div>';


            if (isset($formInputValue['helpUrl'])) {
                $extendFormHtml .= '<a href="'.$formInputValue['helpUrl']['url'].'" target="_blank" class="btn btn-info btn-sm"><i class="fa fa-info-circle"></i> '.$formInputValue['helpUrl']['title'].'</a>';
            }

            $extendFormHtml .= '</div>';
        }

        return $extendFormHtml;
    }
}